import 'dart:async';
import 'dart:ffi';
import 'package:df/page/assets/assets_key.dart';
import 'package:df/page/router/router.dart';
import 'package:df/page/splash/show_other_login.dart';
import 'package:df/service/api_service.dart';
import 'package:df/utils/logger_utils.dart';
import 'package:df/utils/sp_utils.dart';
import 'package:df/widgets/toast_utils.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'dart:io';
import 'package:df/generated/l10n.dart';
import 'package:package_info_plus/package_info_plus.dart';


class Splash {
  static const String kPlatformAndroid = 'android';
  static const String kPlatformIos = 'ios';
  static const String kPlatformOther = 'other';

  /// 当前运行的平台。
  static String vPlatform = kPlatformOther;
  /// 是否显示其他登录方式。
  static bool vShowOtherLogin = false;
  static int versionCode = -1;
  static String versionName = '';
  static String packageName = 'com.ods.digital';
}

class SplashPage extends StatefulWidget {
  const SplashPage({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _SplashPageState();
  }
}


class _SplashPageState extends State<SplashPage> {
  String version = '';

  @override
  void initState() {
    super.initState();

    if (Platform.isAndroid) {
      Splash.vPlatform = Splash.kPlatformAndroid;
    } else if (Platform.isIOS) {
      Splash.vPlatform = Splash.kPlatformIos;
    } else {
      Splash.vPlatform = Splash.kPlatformOther;
    }

    Future.delayed(Duration.zero, () {
      fetchData();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xFF54ABB8),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [

          // 居中的图标
          Expanded(
            child: Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment:  CrossAxisAlignment.center,

                  children: [
                    Image.asset(
                      AssetsKey.kIconLogo,
                      width: 120,
                      height: 120,
                    ),
                    SizedBox(height: 24),
                    Text(
                      '',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 14,
                      ),
                    ),
                  ],
                ),
            ),
          ),

          // 底部版本号
          Container(
            margin: EdgeInsets.only(bottom: 24.0),
            child: Text(
              version,
              style: TextStyle(
                fontSize: 12.0,
                color: Colors.white,
              ),
            ),
          ),
        ],
      ),
    );
  }



  _goWeb(){
    LogUtils.v('【跳转】只能一次');
    GoRouter.of(context).pushNamed(ROUTER_WEB);// 【1/2】不会Flutter的GoRouter用下骚操作
    // GoRouter.of(context).goNamed(ROUTER_WEB);

    //
    // if(RouterId.userId != null && RouterId.userId!.isNotEmpty) {
    //   final Map<String, String?> newQueries = <String, String?> {
    //     SpKey.kSpWechatUnionId: RouterId.wechatUnionId,
    //     SpKey.kSpLarkUnionId: RouterId.larkUnionId,
    //     SpKey.kSpUserId: RouterId.userId,
    //   };
    //   GoRouter.of(context).goNamed(ROUTER_WEB, queryParameters: newQueries);
    // } else {
    //   GoRouter.of(context).goNamed(ROUTER_LOGIN);
    // }
  }

  void fetchData() async {
    const int goWebDelay = 2000;
    DateTime startTime = DateTime.now();
    LogUtils.e('【等待】开始耗时= ${startTime}');//TODO 1

    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    DateTime fromPlatformTime = DateTime.now();
    LogUtils.e('【等待】获取版本结束= ${fromPlatformTime}');//TODO 2
    LogUtils.v("【其他登录】耗时操作2：获取版本= ${packageInfo}");
    Splash.versionCode = int.parse(packageInfo.buildNumber);
    Splash.versionName = packageInfo.version;
    Splash.packageName = packageInfo.packageName;
    updateVersion(Splash.versionName);
    LogUtils.v("【其他登录】版本= ${Splash.versionCode}");

    ShowOtherLogin response = await ApiService.getShowOtherLogin();
    DateTime getShowOtherLoginTime = DateTime.now();
    LogUtils.e('【等待】第三方结束= ${getShowOtherLoginTime}');//TODO 3
    LogUtils.v("【其他登录】耗时操作1：请求网络= ${response.resultMsg}");
    int code = response.resultCode;
    Data? data = response.data;
    LogUtils.v("【其他登录】结果= ${code}");
    if(code == ApiService.kCodeSuccess) {
      LogUtils.v('【其他登录】成功= ${data}');

      Splash.vShowOtherLogin = data != null ? data.show : false;
      LogUtils.v('【其他登录】全平台显示= ${Splash.vShowOtherLogin}');
      DataPlatform? androidData = data?.android;
      DataPlatform? iosData = data?.ios;
      LogUtils.v("【其他登录】后台Android= ${androidData}");
      LogUtils.v("【其他登录】后台iOS= ${iosData}");

      if (Splash.vPlatform == Splash.kPlatformIos) {
        if(iosData != null) {
          if (iosData.minVersionCode <= Splash.versionCode && Splash.versionCode <= iosData.maxVersionCode) {
            Splash.vShowOtherLogin = iosData.show;
            LogUtils.v('【其他登录】平台= ${Splash.vPlatform}，显示= ${Splash.vShowOtherLogin}');
          }
        }
      } else if (Splash.vPlatform == Splash.kPlatformAndroid) {
        if(androidData != null) {
          if (androidData.minVersionCode <= Splash.versionCode && Splash.versionCode <= androidData.maxVersionCode) {
            Splash.vShowOtherLogin = androidData.show;
            LogUtils.v('【其他登录】平台= ${Splash.vPlatform}，显示= ${Splash.vShowOtherLogin}');
          }
        }
      } else {
        LogUtils.v('【其他登录】平台= ${Splash.vPlatform}，显示= ${response.data}');
      }
    } else {
      LogUtils.v('【其他登录】失败= ${code}');
    }


    setState(() {
      // 耗时操作后更新UI
    });


    DateTime endTime = DateTime.now();
    Duration elapsedTime = endTime.difference(startTime);
    // 计算剩余的延迟时间
    int remainingDelay = goWebDelay - elapsedTime.inMilliseconds;
    if (remainingDelay <= 0) {
      LogUtils.e('【等待】耗时(太)长；延迟= ${remainingDelay} = ${endTime} - ${startTime}');
      _goWeb();
    } else {
      LogUtils.e('【等待】耗时时长；延迟= ${remainingDelay} = ${endTime} - ${startTime}');
      Future.delayed(Duration(milliseconds: remainingDelay), _goWeb);
    }

  }

  // 在需要更新版本号时调用此方法
  void updateVersion(String newVersion) {
    setState(() {
      // version = 'v${newVersion}';
      version = newVersion;
    });
  }

}
